"ui";
let Config = require('./Config');
var DeviceModule = require('./DeviceModule');
var NekoBoxManager = require('./NekoBoxManager');
let Util = require('./Util');
let amazonIP = '';

var deviceModule = new DeviceModule();
// console.log(' deviceModule = ' , deviceModule);
// console.log(' util = ' , util);

let EventConfig = {
    DEVICE_CHANGED : 'DEVICE_CHANGED',
    IP_CHANGED : 'IP_CHANGED',
    NEKO_ADDICON_DOWNLOADED : 'NEKO_ADDICON_DOWNLOADED',
    FIND_IMAGE : 'FIND_IMAGE',
};

ui.layout(
    <vertical padding="16">
        <button id="btnChangeDevice" text="变换设备" />
        <button id="btnChangeIP" text="变换IP" />
        <button id="btnNekoBox" text="代理IP" />
        <button id="btnCheck" text="是否有VMess" />
        <button id="btnLaunch" text="启动包"/>

        <text id="txtReady" text="准备中:"/>
        <text id="txtGaid" text="gaid:"/>
        <text id="txtOS" text="os:"/>
        <text id="txtApiLevel" text="api_level:"/>
        <text id="txtBrand" text="brand:"/>
        <text id="txtBrandName" text="brand_name:"/>
        <text id="txtHardware" text="hardware:"/>
        <text id="txtModel" text="model:"/>
        <text id="txtRevision" text="revision:"/>
        <text id="txtHdr" text="hdr:"/>
        <text id="txtXDPI" text="xdpi:"/>
        <text id="txtYDPI" text="ydpi:"/>
        <text id="txtIP" text="ip:"/>
    </vertical>
);

// 创建一个事件监听器，等待子线程传递数据
events.observeKey();
events.on(EventConfig.DEVICE_CHANGED, function(str) {
    toastLog('DEVICE_CHANGED = ' + str);
    let body = JSON.parse(str);
    log("主线程收到数据: " , body);
    deviceModule.handleChangeDevice(body.ret);
    updateView();
});

events.on(EventConfig.IP_CHANGED, function(str) {
    let body = JSON.parse(str);
    let ip = body.ret;
    if(ip == null){
        return;
    }
    ui.txtIP.setText(`ip:${ip}`);
    amazonIP = ip;
});

events.on(EventConfig.NEKO_ADDICON_DOWNLOADED, function(image){
    console.log('------NEKO_ADDICON_DOWNLOADED image = ' , image);
    nekoAddIcon = image;
    ui.txtReady.setText('准备完毕');
});

events.on(EventConfig.FIND_IMAGE,function(ret){
    console.log(`------FIND_IMAGE ret = ` , ret);
});

ui.btnCheck.click(()=>{
    // app.launch('moe.nb4a');
    // threads.start(function() {
    // });
    let img = images.read('/sdcard/Pictures/app_icon.png');
    if(img != null){
        console.log("已找到");
    }else{
        console.log("未找到");
    }
});

ui.btnNekoBox.click(()=>{
    let packageName = 'moe.nb4a';
    Util.killApp(packageName);
    Util.clearAppData(packageName);
    app.launch(packageName);
    threads.start(function() {
        NekoBoxManager.createVMess(amazonIP);
        sleep(1000);
        NekoBoxManager.connect();
        NekoBoxManager.testFocus();
    });
});

ui.btnChangeIP.click(()=>{
    threads.start(function() {
        // 向服务器发送http请求
        var url = `${Config.ServerURL}/ChangeIP`;
        try {
            let r = http.postJson(url,{});
            let str = r.body.string();
            events.emit(EventConfig.IP_CHANGED, str);
        } catch (error) {
            console.log('error = ' , error);
        }
    });
});


ui.btnChangeDevice.click(()=>{
    threads.start(function() {
        // 向服务器发送http请求
        // console.log('111111111');
        var url = `${Config.ServerURL}/RandomDevice`;
        try {
            // console.log('2222222222');
            let r = http.postJson(url,{
            });
            // console.log('3333333333');
            let str = r.body.string();
            // console.log('4444444444');
            // console.log('body = ' , body , ' type = ' , typeof(body));
            events.emit(EventConfig.DEVICE_CHANGED, str);
            // console.log('5555555555');
        } catch (error) {
            // console.log('error = ' , error);
            events.emit(EventConfig.DEVICE_CHANGED, error);
        }
    });
});

ui.btnLaunch.click(function(){
    app.launch('moe.nb4a');
    // setTimeout();
    // auto.waitFor();
    // var sendButton = text("发送").findOne();
    // sendButton.click();
    setTimeout(()=>{
        try {
            console.log('--------timeout');
            // var sendButton = text("Syn AutoJS").findOne();
            // if(sendButton){
            //     console.log('-------autojs clicked');
            //     sendButton.click();
            // }else{
            //     console.log('-------can not find');
            // }
            
        } catch (error) {
            console.log('------error = ' , error);
        }
        
    },5000)
});

function registUser(strI50,strMediate,strDevice){
    var url = `${Config.ServerURL}/RegistUser`;
    try {
        let r = http.postJson(url, {
            i50 : strI50,
            deviceInfo : strDevice,
            mediate : strMediate
        });
        console.log('registUser r = ' , r);
    } catch (error) {
        console.log('error = ' , error);
    }
}

function startDeviceInfoService(){
    var receiver = new android.content.BroadcastReceiver({
        onReceive: function(context, intent) {
            var strI50 = intent.getStringExtra("i50");
            var strMediate = intent.getStringExtra("mediate");
            var strDevice = intent.getStringExtra("device");
            log("Received message: strI50 = " + strI50);
            threads.start(function() {
                registUser(strI50,strMediate,strDevice);
            });
        }
    });
    
    var filter = new android.content.IntentFilter("SYN_AUTOHJS");
    context.registerReceiver(receiver, filter);
}

function updateView(){
    let str = deviceModule.getCurrentDeviceInfo();
    if(!str){
        return;
    }
    let data = JSON.parse(str);
    ui.txtOS.setText(`os:${data.os}`);
    ui.txtApiLevel.setText(`api_level:${data.api_level}`);
    ui.txtBrand.setText(`brand:${data.brand}`);
    ui.txtBrandName.setText(`brand_name:${data.brand_name}`);
    ui.txtHardware.setText(`hardware:${data.hardware}`);
    ui.txtModel.setText(`model:${data.model}`);
    ui.txtRevision.setText(`revision:${data.revision}`);
    ui.txtHdr.setText(`hdr:${data.hdr}`);
    ui.txtXDPI.setText(`xdpi:${data.xdpi}`);
    ui.txtYDPI.setText(`ydpi:${data.ydpi}`);
    if(data.gaid != null){
        ui.txtGaid.setText(`gaid:${data.gaid}`);
    }
}

function update(){
    // console.log('111111111');
}

let intervalSecs = 1;
setInterval(() => {
    update();
}, intervalSecs * 1000);

startDeviceInfoService();
updateView();
// let image = util.download('/sdcard/nekobox_addip.png','https://pushtrain.oss-cn-hangzhou.aliyuncs.com/AdProject/nekobox_addip.png');
// https://pushtrain.oss-cn-hangzhou.aliyuncs.com/AdProject/nekobox_addip.png